package com.giantlizard.cloud.base.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

public class IpUtil {

    private static final String UNKNOWN = "unknown";
    private static final String FIXED_IP_FOR_INTERNET = "127.0.0.1"; // 或者你想要的任何固定IP
    private static final Pattern PRIVATE_IP_PATTERN =
            Pattern.compile("^(10|127)\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$|" +
                    "^192\\.168\\.\\d{1,3}\\.\\d{1,3}$|" +
                    "^172\\.(1[6-9]|2[0-9]|3[0-1])\\.\\d{1,3}\\.\\d{1,3}$");

    private static final String[] HEADERS_TO_TRY = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_CLIENT_IP",
            "X-Real-IP"
    };

    public static String getIpAddress(HttpServletRequest request) {
        for (String header : HEADERS_TO_TRY) {
            String ipList = request.getHeader(header);
            if (ipList != null && !UNKNOWN.equalsIgnoreCase(ipList)) {
                // 处理多个IP的情况，取第一个
                String ip = extractFirstIp(ipList);
                if (!isPrivateIp(ip)) {
                    return ip;
                }
            }
        }
        // 如果所有代理头都没有，则尝试从远程地址获取
        String remoteAddr = request.getRemoteAddr();
        if (!isPrivateIp(remoteAddr)) {
            return remoteAddr;
        }
        return FIXED_IP_FOR_INTERNET;
    }

    private static boolean isPrivateIp(String ip) {
        return PRIVATE_IP_PATTERN.matcher(ip).matches();
    }

    private static String extractFirstIp(String ipList) {
        // 分割字符串并返回第一个IP
        String[] parts = ipList.split(",");
        return parts[0].trim();
    }

    public static String getIpAddress() {
        return getIpAddress(ServletUtils.getRequest());
    }
}